package com.lagou.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端
 */
public class NIOClient {

    public static void main(String[] args) throws IOException {
        //1. 打开通道
        SocketChannel socketChannel = SocketChannel.open();
        //2. 设置连接IP和端口号
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        System.out.println("客户端已连接==============");
        //3. 写出数据
        socketChannel.write(ByteBuffer.wrap("我是客户端，收到请回复".getBytes()));
        //4. 读取服务器写回的数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(byteBuffer);
        System.out.println("服务端发送的消息：" + new String(byteBuffer.array(), 0 , read));
        // 5. 释放资源
        socketChannel.close();
    }
}
